﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Data.Common;
using MYLSOFT.JsonSimple;
using com.byt.webcore.utils;

namespace com.byt.webcore.utils.tree
{
    public class Tree
    {


        protected Dictionary<string, Node> nodes;
        protected Node root;

        public Tree()
        {
            nodes = new Dictionary<string, Node>();
            root = new Node();
        }

        public Tree(DbDataReader rs, string nameNodeChilds)
        {
            nodes = new Dictionary<string, Node>();
            root = new Node();

            while (rs.Read())
            {

                JSONObject jo = Utils.getJSONObject(rs);
                Node n = new Node(nameNodeChilds);
                foreach (string key in jo.Keys)
                {
                    n.Add(key, jo[key]);
                }

                add((string)rs["id"], n, (string)rs["idsup"]);
            }
        }

        /*
        public Node add(string key, Node node, string parentKey) {
            if(Utils.isNullOrEmpty(parentKey))
                parentKey = "__null";
            Node parent = nodes.get(parentKey);

            if (parent == null) {
                root.add(node);
            } else {
                parent.add(node);
            }
            nodes.put(key, node);
            return node;
        }
    */

        public Node add(string key, Node node, string parentKey)
        {
            Node parent = null;
            if (string.IsNullOrEmpty(parentKey))
            {
                parent = root;
            }
            else
            {
                parent = nodes.ContainsKey(parentKey) ? nodes[parentKey] : root;
            }
            parent.Add(node);
            nodes.Add(key, node);
            return node;
        }

        public JSONArray ToJSON()
        {
            Object r = root[root.labelChilds];
            if (r == null)
                return new JSONArray();
            return (JSONArray)r;
        }

        override public string ToString()
        {
            return ToJSON().ToString();
        }


    }
}
